package com.example.Film.reviews.website.security;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

import javax.sql.DataSource;

@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Autowired
    DataSource dataSource;

    @Autowired
    BCryptPasswordEncoder bCryptPasswordEncoder;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.jdbcAuthentication().dataSource(dataSource)
                .usersByUsernameQuery("SELECT username, password, enabled " + "FROM user_accounts WHERE username = ?")
                .authoritiesByUsernameQuery("SELECT username, role " + "FROM user_accounts WHERE username = ?")
                .passwordEncoder(new BCryptPasswordEncoder());


//        builder.inMemoryAuthentication()
//                .passwordEncoder(new BCryptPasswordEncoder())
//                .withUser("tom")
//                .password(new BCryptPasswordEncoder().encode("123"))
//                .roles("USER")
//                .and()
//                .withUser("jerry")
//                .password("456")
//                .authorities("USER")
        ;
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()

//                .antMatchers("/evaluations/new").hasRole("USER")
//                .antMatchers("/box_offices/new").hasRole("USER")
//                .antMatchers("/directors/new").hasRole("USER")
//                .antMatchers("/performers/new").hasRole("USER")
//                .antMatchers("/movies/new").hasRole("USER")
                .antMatchers("/").authenticated().and().formLogin();
    }

    @Bean
    public PasswordEncoder getPasswordEncoder(){
        return NoOpPasswordEncoder.getInstance();
    }
}